package com.yhsimon.realm.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yhsimon.realm.member.entity.article.ArticleEntity;
import com.yhsimon.realm.member.entity.article.CommentEntity;
import com.yhsimon.realm.member.entity.user.UserEntity;
import com.yhsimon.realm.member.mapper.ArticleMapper;
import com.yhsimon.realm.member.mapper.UserMapper;
import com.yhsimon.realm.member.service.CommentService;
import com.yhsimon.realm.member.mapper.CommentMapper;
import com.yhsimon.realm.member.vo.article.CommentVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 19819
 * @description 针对表【ums_comment(评论信息表)】的数据库操作Service实现
 * @createDate 2024-05-06 17:43:45
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentEntity>
        implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public List<CommentVo> listCommentByArticleId(long articleId,String userId) {

        // <commentId,parentId>
        Map<Long, Long> commentRelationMap = new HashMap<>();
        // <一级评论id,CommentVo>
        Map<Long, CommentVo> commentMap = new HashMap<>();

        // 1. 构造commentRelationMap
        List<CommentEntity> allCommentEntityList = commentMapper.selectList(new QueryWrapper<CommentEntity>().eq("article_id", articleId).eq("is_deleted", 0));
        for (CommentEntity commentEntity : allCommentEntityList) {
            commentRelationMap.put(commentEntity.getId(), commentEntity.getParentId());
            // 2 构造一级评论Vo
            if (commentEntity.getType() == 0) {
                UserEntity userEntity = userMapper.selectById(commentEntity.getCommentatorId());
                CommentVo commentVo = new CommentVo();
                BeanUtils.copyProperties(commentEntity, commentVo);
                commentVo.setCommentatorName(userEntity.getNickname());
                commentVo.setCommentatorAvatar(userEntity.getAvatar());
                commentVo.setLikeComment(isLikeComment(commentEntity.getId()+"",userId));
                // 从redis中获取点赞数
                String key = "comment:like:" + commentEntity.getId();
                SetOperations<String, String> setOperations = redisTemplate.opsForSet();
                Long likeCount = setOperations.size(key);
                commentVo.setLikeCount(likeCount == null ? 0 : likeCount.intValue());
                commentMap.put(commentEntity.getId(), commentVo);
            }
        }


        // 3. 再查找二级评论
        for (CommentEntity subCommentEntity : allCommentEntityList) {
            // 4. 二级评论Vo数据补充
            if (subCommentEntity.getType() == 1) {
                UserEntity userEntity = userMapper.selectById(subCommentEntity.getCommentatorId());
                CommentEntity parentCommentEntity = commentMapper.selectById(subCommentEntity.getParentId());
                Long commentatorId = parentCommentEntity.getCommentatorId();
                UserEntity parentUserEntity = userMapper.selectById(commentatorId);
                CommentVo subCommentVo = new CommentVo();
                BeanUtils.copyProperties(subCommentEntity, subCommentVo);
                subCommentVo.setCommentatorName(userEntity.getNickname());
                subCommentVo.setCommentatorAvatar(userEntity.getAvatar());
                subCommentVo.setParentCommentatorId(commentatorId);
                subCommentVo.setParentCommentatorName(parentUserEntity.getNickname());
                subCommentVo.setLikeComment(isLikeComment(subCommentEntity.getId()+"",userId));
                // 从redis中获取点赞数
                String key = "comment:like:" + subCommentEntity.getId();
                SetOperations<String, String> setOperations = redisTemplate.opsForSet();
                Long likeCount = setOperations.size(key);
                subCommentVo.setLikeCount(likeCount == null ? 0 : likeCount.intValue());

                // 5. 二级评论所在的一级评论ID
                long commentId = subCommentEntity.getParentId();
                while (commentRelationMap.get(commentId) != -1) {
                    commentId = commentRelationMap.get(commentId);
                }
                CommentVo commentVo = commentMap.get(commentId);

                // 6. 设置一级评论的二级评论集合
                List<CommentVo> subCommentVoList = commentVo.getCommentVoList();
                if (subCommentVoList == null) {
                    subCommentVoList = new ArrayList<>();
                }
                subCommentVoList.add(subCommentVo);
                commentVo.setCommentVoList(subCommentVoList);
                // 7. 更新commentMap
                commentMap.put(commentId, commentVo);
            }
        }

        // 8. 结果构造
        List<CommentVo> commentVoList = new ArrayList<>();
        for (Map.Entry<Long, CommentVo> entry : commentMap.entrySet()) {
            commentVoList.add(entry.getValue());
        }
        return commentVoList;
    }

    @Override
    public boolean saveComment(CommentEntity commentEntity) {
        try {
            ArticleEntity articleEntity = articleMapper.selectById(commentEntity.getArticleId());
            if (articleEntity != null) {
                commentMapper.insert(commentEntity);
                Long commentCount = commentMapper.selectCount(new QueryWrapper<CommentEntity>().eq("article_id", articleEntity.getId()));
                articleEntity.setCommentCount(commentCount.intValue());
                articleMapper.updateById(articleEntity);
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public void likeComment(String id, String userId) {
        String key = "comment:like:" + id;
        SetOperations<String, String> setOperations = redisTemplate.opsForSet();
        if (Boolean.FALSE.equals(setOperations.isMember(key, userId))) {
            setOperations.add(key, userId);
        } else {
            setOperations.remove(key, userId);
        }
    }

    public boolean isLikeComment(String id, String userId) {
        String key = "comment:like:" + id;
        SetOperations<String, String> setOperations = redisTemplate.opsForSet();
        return Boolean.TRUE.equals(setOperations.isMember(key, userId));
    }
}




